package com.xneure.utils;

/**
 * 判断服务器类型
 */
public class ServerDetector{
	public enum ServerType{
		TOMCAT{
			@Override
			public boolean isServer(){
				return _hasSystemProperty("catalina.base");
			}
		},
		WEBLOGIC{
			@Override
			public boolean isServer(){
				return _detect("/weblogic/Server.class");
			}
		},
		WEBSPHERE{
			@Override
			public boolean isServer(){
				return _detect("/com/ibm/websphere/product/VersionInfo.class");
			}
		},
		WILDFLY{
			@Override
			public boolean isServer(){
				return _hasSystemProperty("jboss.home.dir");
			}
		},
		JBOSS{
			@Override
			public boolean isServer(){
				return _hasSystemProperty("jboss.home.dir");
			}
		},
		JETTY{
			@Override
			public boolean isServer(){
				return _hasSystemProperty("jetty.home");
			}
		},
		GLASSFISH{
			@Override
			public boolean isServer(){
				return _hasSystemProperty("com.sun.aas.instanceRoot");
			}
		},
		JONAS{
			@Override
			public boolean isServer(){
				return _hasSystemProperty("jonas.base");
			}
		},
		OC4J{
			@Override
			public boolean isServer(){
				return _detect("oracle.oc4j.util.ClassUtils");
			}
		},
		RESIN{
			@Override
			public boolean isServer(){
				return _hasSystemProperty("resin.home");
			}
		},
		UNKNOWN{
			@Override
			public boolean isServer(){
				return false;
			}
		};
		public abstract boolean isServer();

		private final static boolean _hasSystemProperty(String key){
			return System.getProperty(key) != null;
		}

		private final static boolean _detect(String className){
			try{
				ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
				systemClassLoader.loadClass(className);
				return true;
			}catch(ClassNotFoundException cnfe){
				if(ServerDetector.class.getResource(className) != null){
					return true;
				}
			}
			return false;
		}
	}

	private static final ServerDetector.ServerType _serverType = _detectServerType();
	/**
	 * 当前服务器类型
	 * 
	 * @return ServerDetector.ServerType
	 */
	public static ServerDetector.ServerType getServerType(){
		return _serverType;
	}

	/**
	 * 判断是否支持
	 */
	public static boolean isSupported(String serverType){
		serverType = serverType.toUpperCase();
		for(ServerType st:ServerType.values()){
			if(st.name().equals(serverType)){
				return true;
			}
		}
		return false;
	}

	private static ServerDetector.ServerType _detectServerType(){
		String serverId = System.getProperty("server.detector.server.id");
		if(serverId != null){
			return ServerDetector.ServerType.valueOf(serverId.toUpperCase());
		}
		for(ServerType st:ServerType.values()){
			if(st.isServer()){
				return st;
			}
		}
		return ServerDetector.ServerType.UNKNOWN;
	}
}
